export function useCRUD() {
  const baseURL = '/api';
  
  const createTableAPI = (tableName) => {
    return {
      getAll: async (params = {}) => {
        const queryString = new URLSearchParams(params).toString();
        const response = await fetch(`${baseURL}/${tableName}?${queryString}`);
        return response.json();
      },
      
      getById: async (id) => {
        const response = await fetch(`${baseURL}/${tableName}/${id}`);
        if (response.status === 404) return null;
        return response.json();
      },
      
      create: async (data) => {
        const response = await fetch(`${baseURL}/${tableName}`, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        return response.json();
      },
      
      update: async (id, data) => {
        const response = await fetch(`${baseURL}/${tableName}/${id}`, {
          method: 'PUT',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(data)
        });
        return response.json();
      },
      
      delete: async (id) => {
        await fetch(`${baseURL}/${tableName}/${id}`, {
          method: 'DELETE'
        });
      }
    };
  };
  
  // 从配置中获取表名并创建对应的 API
  const tables = window.__SMART_CRUD_CONFIG__.tables || [];
  const api = {};
  
  tables.forEach(tableName => {
    api[tableName] = createTableAPI(tableName);
  });
  
  return api;
}

export default useCRUD;